//
//  HomeDetailBuyViewController.m
//  GiftNote
//
//  Created by lanou on 15/8/14.
//  Copyright (c) 2015年 GN. All rights reserved.
//

#define kBuyDetail @"http://api.liwushuo.com/v2/items/"  //详情

#import "HomeDetailBuyViewController.h"
#import "HomeHeader.h"
#import "HomeBuyHeadView.h"
#import "LORequestManger.h"
#import "HomeBuyDetailModel.h"
#import "MBProgressHUD+MJ.h"
#import "UMSocial.h"
#import "FMDatabase.h"


@interface HomeDetailBuyViewController ()<UIWebViewDelegate,UMSocialUIDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) HomeBuyDetailModel *buyModel;
@property (nonatomic, strong) UIWebView *desWebView;

@property (nonatomic, strong) HomeBuyHeadView *headView;
@property (nonatomic, strong) UIView *buyView;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *commentArray;

@property (nonatomic, strong) FMDatabase *db;
@property (nonatomic, strong) UIBarButtonItem *rightBarButton;
@property (nonatomic, strong) UIBarButtonItem *shareButton;

@property (nonatomic, strong) NSMutableArray *searchArray; // 从表中检索数据,来判断有没有收藏的记录

@end



@implementation HomeDetailBuyViewController
#pragma mark --- 懒加载
- (NSMutableArray *)dataSource{
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)commentArray{
    
    if (_commentArray == nil) {
        self.commentArray = [NSMutableArray array];
    }
    return _commentArray;
}

- (NSMutableArray *)searchArray{

    if (!_searchArray) {
        self.searchArray = [NSMutableArray arrayWithArray:0];
    }
    return _searchArray;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    //  改变返回按钮的颜色
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    
    self.navigationItem.title = @"礼物详情";
    [MBProgressHUD showMessage:@"正在加载数据..."];
    
    [self readData];
    [self creatCollectionBarButton];
    [self creatCollectionList];
    
}



//  添加收藏按钮和分享按钮
- (void)creatCollectionBarButton{
    
    
    _rightBarButton = [[UIBarButtonItem alloc] initWithTitle:@"三" style:UIBarButtonItemStyleDone target:self action:@selector(addCollection:)];
    _shareButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fenxiang-2"] style:UIBarButtonItemStylePlain target:self action:@selector(shareAction:)];
    
    
    self.navigationItem.rightBarButtonItems = @[_shareButton,_rightBarButton];
    
//    self.navigationItem.rightBarButtonItem = _rightBarButton;
    [self searchData];
}





#pragma mark --- 创建tableView
- (void)creatMainScrollView{
    
    _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, kHomeWidth, kHomeHeight - 49 - 64)];
    _mainScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_mainScrollView];
    
    
    _headView = [[HomeBuyHeadView alloc] initWithFrame:CGRectMake(0, 0, kHomeWidth, [HomeBuyHeadView heightForView:_buyModel])];
    _headView.buyModel = _buyModel;
    [_mainScrollView addSubview:_headView];
    
    _desWebView = [[UIWebView alloc] init];
    _desWebView.delegate = self;
    [_desWebView loadHTMLString:_buyModel.detail_html baseURL:nil];
    [_mainScrollView addSubview:_desWebView];
    
    
    //  添加购买的按钮
    UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    buyButton.frame = CGRectMake(0, kHomeHeight - 40 - 49, kHomeWidth, 40);
    buyButton.backgroundColor = [UIColor redColor];
    [buyButton setTitle:@"去天猫购买" forState:UIControlStateNormal];
    [buyButton addTarget:self action:@selector(buyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buyButton];
}


#pragma mark --- 数据解析
- (void)readData
{
    NSString *url = [kBuyDetail stringByAppendingString:[NSString stringWithFormat:@"%@",_ID]];

    [LORequestManger GET:url success:^(id response) {
        
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *newDic = dic[@"data"];
        _buyModel = [[HomeBuyDetailModel alloc] init];
        [_buyModel setValuesForKeysWithDictionary:newDic];
//        NSLog(@"%@",_buyModel.cover_image_url);
        [self.dataSource addObject:_buyModel];
        [self creatMainScrollView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"error:%@",error);
        
    }];
}


//  设置高度
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    _desWebView.frame = CGRectMake(0, CGRectGetMaxY(_headView.frame) + 10, kHomeWidth, height);
    _mainScrollView.contentSize = CGSizeMake(kHomeWidth, height + 10 + [HomeBuyHeadView heightForView:_buyModel]);
    [MBProgressHUD hideHUD];
}




#pragma mark - 收藏数据
//  创建数据库及表
- (void)creatCollectionList{
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Mine.db"];
    _db = [FMDatabase databaseWithPath:path];
    
    
    if (![_db open]) {
        NSLog(@"打开数据库失败");
    }
    
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS MineGifList (id integer PRIMARY KEY, Name text, Price text, Desp text, Detail_html text, Image_urls blob)"];
}


//  添加收藏记录
- (void)addCollectionData:(HomeBuyDetailModel *)detailModel{
    
    //  给图片数组编码
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:_buyModel.image_urls forKey:@"image_urls"];
    [archiver finishEncoding];
    
    
    //  插入数据
    BOOL res = [_db executeUpdate:@"INSERT INTO MineGifList (id, Name, Price, Desp, Detail_html, Image_urls) VALUES (?,?,?,?,?,?)",_buyModel.ID,_buyModel.name,_buyModel.price,_buyModel.desp,_buyModel.detail_html, data];
    
    
    //  判断是否已经收藏(即是否已经插入)
    if (res) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已经收藏过" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}


//  查询相关记录(用来改变右边的收藏按钮的状态)
- (void)searchData{

//    HomeBuyDetailModel *model = self.dataSource[0];
//    NSLog(@"%@",model);
    FMResultSet *rs = [_db executeQuery:@"SELECT * FROM MineGifList WHERE id = ? ",_buyModel.ID];
    
    while ([rs next]) {
        
        NSString *name = [rs stringForColumn:@"Name"];
        [self.searchArray addObject:name];
    }
    
    [rs close];
}


#pragma mark ---  action
- (void)addCollection:(UIBarButtonItem *)sender{
    
    if (_buyModel.ID) {
        [self addCollectionData:_buyModel];
    }
}


- (void)buyButtonAction:(UIButton *)sender{
    
    if (_buyModel.purchase_url != nil) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_buyModel.purchase_url]];
    }
}


- (void)shareAction:(UIButton *)sender{
    
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_buyModel.cover_image_url]]];
    
    NSString *title = [NSString stringWithFormat:@"%@%@",_buyModel.name,_buyModel.desp];
     [UMSocialData defaultData].extConfig.qqData.title = title;
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55d8577467e58ef78a007fa2"
                                      shareText:title
                                     shareImage:image
                                shareToSnsNames:@[UMShareToQQ,UMShareToQzone,UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban]
                                       delegate:self];
    
    
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ,UMShareToQzone] content:title image:image location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
//            NSLog(@"分享成功！");
        }
    }];
    

    [UMSocialData defaultData].extConfig.qqData.url = _buyModel.url;
    [UMSocialData defaultData].extConfig.qzoneData.url = _buyModel.url;
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
